package com.ycm.config;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;
import java.util.Arrays;

/**
 * Spring Cache配置
 *
 * @author ycm
 * @date 2024-11-15
 */
@Configuration
@EnableCaching
public class CacheConfig {
    @Value("${spring.data.redis.prefix:}")
    private String prefix;

    @Value("${spring.data.redis.live-time}")
    private Duration liveTime;

    /**
     * 配置Cache的Key生成策略
     */
    @Bean("keyGenerator")
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            // Cache Key生成策略： 类名_方法名_方法参数Hash值
            return method.getName() + "_" + Arrays.deepHashCode(params);
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .prefixCacheNameWith(StrUtil.isBlank(prefix) ? "" : StrUtil.appendIfMissing(prefix, ":"))
                .entryTtl(liveTime);

        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(defaultCacheConfig)
                .build();
    }
}
